import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState, AppDispatch } from 'src/store';
import { setDarkMode } from 'src/store/action';
import { ThemeEnum } from 'src/interface/theme';

// 设置亮暗色主题
export default function useThemeDark() {
  const dispatch = useDispatch<AppDispatch>();
  const dark = useSelector((state: RootState) => state.theme.dark);

  const traggerTheme = () => {
    dispatch(setDarkMode(!dark));
  };

  useEffect(() => {
    const htmlAttr = document.documentElement.getAttribute('sloth-theme');
    const currentTheme = dark ? ThemeEnum.Dark : ThemeEnum.Light;
    if (htmlAttr !== currentTheme || !htmlAttr) {
      document.documentElement.setAttribute('sloth-theme', currentTheme);
    }
  }, [dark]);

  return {
    dark,
    traggerTheme,
  };
}
